<?php
class ome_finder_delivery{
    var $detail_basic = "发货单详情";
    var $detail_item = "货品详情";
    private $write = '1';
    var $has_many = array(
       'members' => 'members'
    );

    var $addon_cols = "skuNum,itemNum,bnsContent,delivery_id,status,process,stock_status,deliv_status,expre_status,verify,is_bind,type,bind_key,order_createtime";

    function __construct(){
        if($_GET['ctl'] == 'admin_receipts_print' && $_GET['act'] == 'index'){
            $this->write = '2';
            $this->url = 'admin_receipts_print';
        }elseif($_GET['ctl'] == 'admin_refunded' && $_GET['act'] == 'index'){
            $this->write = '2';
            $this->url = 'admin_refunded';
        }else{
           unset($this->column_op);
        }
    }

    //显示状态
    var $column_process = "发货状态";
    var $column_process_width = "80";
    function column_process($row){
        $render = app::get('ome')->render();
        $stock = $row[$this->col_prefix.'stock_status'];
        $deliv = $row[$this->col_prefix.'deliv_status'];
        $expre = $row[$this->col_prefix.'expre_status'];
        $proc  = $row[$this->col_prefix.'process'];
        $verify= $row[$this->col_prefix.'verify'];
        //未设置的默认是打印发货单，备货单跟快递单算是打印完成
        if ($proc=='true'){
            return '已发货';
        }
        if ($verify=='true'){
            return '已校验';
        }
        if($render->app->getConf('ome.delivery.status.cfg') == ''){
            if ($stock=='false' && $deliv=='false' && $expre=='false'){
                return '未打印';
            }
            if ($stock=='true' && $deliv=='true' && $expre=='true'){
                return '已打印';
            }else {
                return '正在打印';
            }
        }else{
        	$status = $render->app->getConf('ome.delivery.status.cfg');
        	if($status['set']['stock'] ==1 && $status['set']['delie'] == 1){
	        	if ($stock=='false' && $deliv=='false' && $expre=='false'){
	                return '未打印';
	            }
	            if ($stock=='true' && $deliv=='true' && $expre=='true'){
	                return '已打印';
	            }else {
	                return '正在打印';
	            }
        	}
        	if($status['set']['stock'] ==1 && $status['set']['delie'] == 0){
	        	if ($stock=='false' && $deliv=='false' && $expre=='false'){
	                return '未打印';
	            }
	            if ($stock=='true' && $expre=='true'){
	                return '已打印';
	            }else {
	                return '正在打印';
	            }
        	}
        	if($status['set']['stock'] ==0 && $status['set']['delie'] == 1){
	        	if ($stock=='false' && $deliv=='false' && $expre=='false'){
	                return '未打印';
	            }
	            if ($deliv=='true' && $expre=='true'){
	                return '已打印';
	            }else {
	                return '正在打印';
	            }
        	}
        	if($status['set']['stock'] ==0 && $status['set']['delie'] == 0 ){
	        	if ($stock=='false' && $deliv=='false' && $expre=='false'){
	                    return '未打印';
	                }
	                if ($expre=='true'){
	                    return '已打印';
	                }else {
	                    return '正在打印';
	                }

        	}
        }
    }

    //显示状态
    var $column_status = "打印状态";
    var $column_status_width = "80";

    function column_status($row) {

        $stock = $row[$this->col_prefix . 'stock_status'];
        $stockColor = ($stock == 'true') ? 'green' : '#eeeeee';
        $deliv = $row[$this->col_prefix . 'deliv_status'];
        $delivColor = ($deliv == 'true') ? 'red' : '#eeeeee';
        $expre = $row[$this->col_prefix . 'expre_status'];
        $expreColor = ($expre == 'true') ? '#9a6913' : '#eeeeee';
        $ret = $this->getViewPanel('备货单','备', $stockColor);
        $ret .= $this->getViewPanel('发货单', '发',$delivColor);
        $ret .= $this->getViewPanel('快递单', '快',$expreColor);
        return $ret;
    }

    public function getViewPanel($caption, $text,$color) {
        if ($color == '#eeeeee')
            $caption .= '未打印';
        else
            $caption .= '已打印';
        return sprintf("<div style='width:18px;padding:2px;height:16px;color:#eeeeee;background-color:%s;float:left;'><span alt='%s' title='%s'>%s&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></div>",
                $color, $caption, $caption,$text);
    }

    //显示状态
    var $column_create = "下单到现在";
    var $column_create_width = "100";
    var $column_create_order_field= 'order_createtime';

    function column_create($row) {

        $time = $row[$this->col_prefix . 'order_createtime'];
        $status = $row[$this->col_prefix . 'status'];
        $now = time();
        $beforeNow = $now - $time;
        $beforeNow = $beforeNow >0 ?$beforeNow : 0;
        $days = intval($beforeNow / 86400);
        if ($status == 'progress' || $status == 'ready') {
            if ($days >= 7) {
                $ret = "<div style='width:90px;height:20px;background-color:red;color:#FFFFFF;text-align:center;'>超过一周</div>";
            } elseif ($days >= 1) {
                $ret = "<div style='width:90px;height:20px;background-color:blue;color:#FFFFFF;text-align:center;'>" . $this->_genDayStr($beforeNow) . "</div>";
            } else {
                $ret = "<div style='width:90px;height:20px;background-color:green;color:#FFFFFF;text-align:center;'>" . $this->_genDayStr($beforeNow) . "</div>";
            }
        } else {
            $ret = "<div style='width:90px;height:20px;background-color:#dddddd;color:#FFFFFF;text-align:center;'>完成</div>";
        }
        return $ret;
    }

    function _genDayStr($time) {

        $d = intval($time / 86400);
        $ret = ($d >0) ? "{$d}天" : "";
        $h = intval(($time - $d*86400) / 3600);
        $ret .= "{$h}小时";
        $m = intval(($time - $d*86400 - $h*3600) / 60);
        $ret .= "{$m}分";

        return $ret;
    }

    //显示状态
    var $column_content = "订单内容";
    var $column_content_width = "160";
    var $column_content_orderas = "idx_split";

    function column_content($row) {

        $skuNum = $row[$this->col_prefix . 'skuNum'];
        $itemNum = $row[$this->col_prefix . 'itemNum'];
        $content = $row[$this->col_prefix . 'bnsContent'];

        $cnts = unserialize($content);
        $cnt = sprintf("共有 %d 种商品，总共数量为 %d 件， 具体 SKU 为： %s", $skuNum, $itemNum, @implode(', ', $cnts));

        @reset($cnts);
        $content = $cnts[@key($cnts)];
        if ($skuNum >1) {

            $content .= ' 等';
        }

        return sprintf("<span alt='%s' title='%s'><font color='red'>(%d / %d)</font> %s</span>",$cnt, $cnt, $skuNum, $itemNum, $content);
    }

    function detail_basic($dly_id){
        $render = app::get('ome')->render();
        $dlyObj = &app::get('ome')->model('delivery');
        $orderObj = &app::get('ome')->model('orders');
        $braObj = &app::get('ome')->model('branch');
        $opObj  = &app::get('ome')->model('operation_log');
        $log['obj_id'] = $dly_id;
        $log['obj_type'] = "delivery@ome";
        $logdata = $opObj->read_log($log, 0, -1);
        $dly = $dlyObj->dump($dly_id);
        $tmp = app::get('ome')->model('members')->dump($dly['member_id']);
        $dly['member_name'] = $tmp['account']['uname'];
        $dly['members'] = "手机：".$tmp['contact']['phone']['mobile']."<br>";
        $dly['members'] .= "电话：".$tmp['contact']['phone']['telephone']."<br>";
        empty($dly['branch_id'])?$branch_id=0:$branch_id=$dly['branch_id'];
        $shop = $dlyObj->getShopInfo($dly['shop_id']);
        $dly['area'] = $shop['area'];

        $orderIds = $dlyObj->getOrderIdByDeliveryId($dly_id);
        /*$sql = "SELECT dc.* FROM sdb_ome_branch_area ba
                                LEFT JOIN sdb_ome_dly_corp_area dca
                                    ON ba.region_id=dca.region_id
                                LEFT JOIN sdb_ome_dly_corp  dc
                                    ON dca.corp_id=dc.corp_id WHERE ba.branch_id='$branch_id'";*/
        if ($orderIds)
        $ids = implode(',', $orderIds);
        if ($orderIds)
        foreach ($orderIds as $oid)
        {
            $order = $orderObj->dump($oid);
            $order_bn[] = $order['order_bn'];
        }


		foreach($logdata as $k=>$v){
			$logdata[$k]['operate_time'] = date('Y-m-d H:i:s',$v['operate_time']);
		}
		
        $render->pagedata['write']    = $this->write;
        $render->pagedata['url']    = $this->url;
        $render->pagedata['log']      = $logdata;
        $render->pagedata['dly_corp'] = $braObj->get_corp($branch_id);//$dlyObj->db->select($sql);
		$dly['create_time'] = date('Y-m-d H:i:s',$dly['create_time']);
        $render->pagedata['dly']      = $dly;
        $render->pagedata['order_bn'] = $order_bn;
        //echo "<pre>";
        //print_r($render->pagedata['dly']);die;
        $render->pagedata['status'] = $_GET['status'];

        return $render->fetch('admin/delivery/delivery_detail.html');
    }

    function detail_item($dly_id){
        $render = app::get('ome')->render();
        $dlyObj = &app::get('ome')->model('delivery');
        $pObj = &app::get('ome')->model('products');
        $items = $dlyObj->getItemsByDeliveryId($dly_id);
        $delivery = $dlyObj->dump($dly_id);
        if ($items)
        foreach ($items as $key => $item){
        	//将商品的显示名称改为后台的显示名称
        	//echo $items[$key]['bn'];
        	$product_name = $pObj->getList('name',array('product_id'=>$items[$key]['product_id']));
            //$item_pos = $dlyObj->getItemPosByItemId($item['item_id']);
            $items[$key]['product_name'] = $product_name[0]['name'];
            //$items[$key]['haspos'] = $item_pos;
            //$items[$key]['pos']    = $dlyObj->getBranchProductPosNum($delivery['branch_id'], $item['product_id']);
        }
        $render->pagedata['write'] = $this->write;
        $render->pagedata['items'] = $items;
        $render->pagedata['dly']   = $delivery;

        return $render->fetch('admin/delivery/delivery_item.html');
    }


    var $column_op = "操作";
    var $column_op_width = "70";

    function column_op($row){

        $id = $row[$this->col_prefix.'delivery_id'];

        $dlyObj = &app::get('ome')->model('delivery');

        //$data = $dlyObj->dump($id);
        $data['status']     = $row[$this->col_prefix.'status'];
        $data['process']    = $row[$this->col_prefix.'process'];
        $data['is_bind']    = $row[$this->col_prefix.'is_bind'];
        $data['type']       = $row[$this->col_prefix.'type'];
        $data['logi_no']    = $row['logi_no'];
        $data['bind_key']    = $row[$this->col_prefix.'bind_key'];

        $filter['process']  = 'false';
        $filter['status']   = array('ready','progress');
        $filter['type']     = 'normal';
        $filter['parent_id'] = '0';
        $filter['bind_key'] = $data['bind_key'];
        $num = $dlyObj->count($filter);
        $finder_id = $_GET['_finder']['finder_id'];
        $button = <<<EOF
        <a href="index.php?app=ome&ctl=admin_receipts_print&act=merge&p[0]=$id&finder_id=$finder_id" target="_blank" alt="可以合并多张发货单">合并</a>
EOF;
        $button2 = <<<EOF
        <a href="index.php?app=ome&ctl=admin_receipts_print&act=split&p[0]=$id&finder_id=$finder_id" target="_blank" alt="可将合并的发货单拆分为单个发货单">拆分</a>
EOF;
        $button3 = <<<EOF
        <input type="button" title="打印物流运单号" name="print" value="打印" onClick="javascript:window.open('index.php?app=ome&ctl=admin_receipts_print&act=toPrintShip&p[0]=$id')" />
EOF;
        $string = '';
        //拆分
        if ($data['is_bind'] == 'true' && $data['process'] == 'false' && $data['status'] != 'succ'){
            $string .= $button2;
        }
        //合并
        if ($num > 1 && $data['is_bind']=='false' && $data['status'] != 'back' && $data['status'] != 'cancel' && $data['status'] != 'stop' && $data['process'] == 'false' && $data['type'] == 'normal'){
            $string .= $button;
        }
        //打印物流运单号
        //$string .= $button3;

        return $string;
    }


	var $column_ident = "批次号";
    var $column_ident_width = "160";
    var $_existIdentItems = array();

    function column_ident($row) {
        if(!isset($this->_existIdentItems[$row['delivery_id']])){
           $objQueue = kernel::single('ome_queue');
           $queueItems = $objQueue->getSimilarQueueItems($row['delivery_id']);
           if($queueItems){
               foreach($queueItems as $k=>$v)$this->_existIdentItems[$k] = $v;
           }
        }

        $ident = isset($this->_existIdentItems[$row['delivery_id']]) ? $this->_existIdentItems[$row['delivery_id']] : '';
        return $ident;
    }
}
?>